package com.auto.learning.activity;

import java.io.File;
import java.io.FileInputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.auto.learning.R;
import com.auto.learning.bean.UserInfoBean;
import com.auto.learning.net.Cache;
import com.auto.learning.net.DownLoadInfo;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.MyProgressDialog;

/**
 * 修改用户头像对话框
 *
 */
@SuppressLint({ "HandlerLeak", "ClickableViewAccessibility" })
public class ChangeUserHead extends Activity {
	
	public final static int PUBLIC_UPDATAHEAD_SUCCESS = 0x15;// 上传头像成功
	public final static int PUBLIC_UPDATAHEAD_FAIL = 0x16;// 上传头像成功
	public final static int PUBLIC_SENDAUDIO_SUCCESS = 0x6;// 上传音频成功
	public final static int PUBLIC_SENDAUDIO_FAIL = 0x7;// 上传音频失败
	// 裁剪大小
	private final static int ax = 1;
	private final static int ay = 1;
	private final static int ox = 100;
	private final static int oy = 100;
	private LinearLayout bottomLayout;
	private RelativeLayout mainLayout;
	private ImageView transparentView;
	private String faceUrl;// 头像url
	public MyProgressDialog progressDialog;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			if (progressDialog != null) {
				progressDialog.cancel();
			}
			switch (msg.what) {
			case 0x111:
				mainLayout.setBackgroundColor(Color.parseColor("#20000000"));
				break;
			case PUBLIC_UPDATAHEAD_SUCCESS:
				CommonMethod.makeNotice(ChangeUserHead.this, getString(R.string.change_head_success));
				UserInfoBean userInfo = MyUserInfo.getInstance().getUserInfoBean();
				if (userInfo != null) {
					userInfo.setFaceUrl(faceUrl);
				}
				Cache.cacheUserInfo2Local(userInfo);
				closeActivity();
				break;
			case PUBLIC_UPDATAHEAD_FAIL:
				CommonMethod.makeNotice(ChangeUserHead.this, getString(R.string.change_head_fail));
				closeActivity();
				break;
			case PUBLIC_SENDAUDIO_SUCCESS:
				faceUrl = msg.obj.toString();
				new Thread() {
					@Override
					public void run() {
						CommonMethod.updataHead(ChangeUserHead.this, faceUrl,
								handler);
					};
				}.start();
				break;
			case PUBLIC_SENDAUDIO_FAIL:
				CommonMethod
						.makeNotice(ChangeUserHead.this, msg.obj.toString());
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_changeuserhead);
		initUI();
	}

	/**
	 * 初始化UI
	 */
	private void initUI() {
		progressDialog = MyProgressDialog.createLoadingDialog(this);
		mainLayout = (RelativeLayout) findViewById(R.id.ac_cuh_mainlayout);
		bottomLayout = (LinearLayout) findViewById(R.id.ac_cuh_bottom);
		transparentView = (ImageView) findViewById(R.id.ac_cuh_imageview);
		transparentView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				closeActivity();
				return false;
			}
		});

		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0x111);
				this.cancel();
			}
		}, 400, 10);
	}

	/**
	 * 按钮点击
	 *
	 * @param v
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ac_cuh_localbtn:
			choosePicByLocal();
			bottomLayout.setVisibility(View.GONE);
			break;
		case R.id.ac_cuh_camerabtn:
			choosePicByCamera();
			bottomLayout.setVisibility(View.GONE);
			break;
		case R.id.ac_cuh_cancelbtn:
			closeActivity();
			break;
		}
	}

	/**
	 * 选择本地图片
	 */
	private void choosePicByLocal() {
		File file = new File(CommonMethod.getSDPath() + DownLoadInfo.HEAD_DIR);
		if (!file.exists()) {
			file.mkdirs();
		}
		Intent intentAlbum = new Intent(Intent.ACTION_GET_CONTENT);
		intentAlbum.setType("image/*");
		intentAlbum.putExtra("crop", "true");
		intentAlbum.putExtra("aspectX", ax);
		intentAlbum.putExtra("aspectY", ay);
		intentAlbum.putExtra("outputX", ox);
		intentAlbum.putExtra("outputY", oy);
		intentAlbum.putExtra("scale", true);
		intentAlbum.putExtra("return-data", false);
		intentAlbum.putExtra(
				MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(CommonMethod.getSDPath()
						+ DownLoadInfo.HEAD_DIR + "/myhead.png")));
		intentAlbum.putExtra("outputFormat",
				Bitmap.CompressFormat.PNG.toString());
		intentAlbum.putExtra("noFaceDetection", true);
		startActivityForResult(intentAlbum, 0);
	}
	
	

	Uri cameraUri;
	/**
	 * 相机
	 */
	private void choosePicByCamera() {
		File file = new File(CommonMethod.getSDPath() + DownLoadInfo.HEAD_DIR);
		if (!file.exists()) {
			file.mkdirs();
		}
		Intent intentAlbum = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String mPath = CommonMethod.getSDPath() + DownLoadInfo.HEAD_DIR + "/myhead.png";
		// 必须确保文件夹路径存在，否则拍照后无法完成回调
		cameraUri = Uri.fromFile(new File(mPath));
		intentAlbum.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(intentAlbum, 1);
	}

	/**
	 * 退出动画
	 */
	private void closeActivity() {
		mainLayout.setBackgroundColor(Color.parseColor("#00000000"));
		setResult(201);
		this.finish();
		overridePendingTransition(0, R.anim.changehead_out);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			closeActivity();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			closeActivity();
			return;
		}
		if (requestCode == 0) {
			if (data == null) {
				closeActivity();
				return;
			} else {
				Bundle bundle = data.getExtras();
				if (bundle == null) {// 华为一类机子根本不能出现裁剪那个动作
					ContentResolver resolver = getContentResolver();
					// 照片的原始资源地址
					Uri originalUri = data.getData();
					try {
						// 使用ContentProvider通过URI获取原始图片
						Bitmap photo = MediaStore.Images.Media.getBitmap(
								resolver, originalUri);
						photo = CommonMethod.zoomImg(photo, ox, oy);
						CommonMethod.savePhotoToSDCard(photo, "myhead");
					} catch (Exception e) {

					}
				}
			}
		} else if (requestCode == 1) {
			Uri imageUri ;
			if (data != null && data.getData() != null) {
				imageUri = data.getData();
			}else {
				imageUri = cameraUri;
			}
	        Intent intent = new Intent("com.android.camera.action.CROP"); //剪裁
	        intent.setDataAndType(imageUri, "image/*");
	        intent.putExtra("scale", true);
	        //设置宽高比例
	        intent.putExtra("aspectX", 1);
	        intent.putExtra("aspectY", 1);
	        //设置裁剪图片宽高
	        intent.putExtra("outputX", 340);
	        intent.putExtra("outputY", 340);
	        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
	        //广播刷新相册 
	        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	        intentBc.setData(imageUri);     
	        this.sendBroadcast(intentBc);    
	        startActivityForResult(intent, 2); //设置裁剪参数显示图片至ImageView
		} else if (requestCode == 2) {
			BitmapFactory.Options bfOptions=new BitmapFactory.Options(); 
			bfOptions.inDither=false; 
			bfOptions.inPurgeable=true; 
			bfOptions.inTempStorage = new byte[12 * 1024];  
			bfOptions.inJustDecodeBounds = true; 
			File file = new File(CommonMethod.getSDPath() + DownLoadInfo.HEAD_DIR + "/myhead.png".toString()); 
			FileInputStream fs=null; 
			Bitmap bmp = null; 
			try { 
			    fs = new FileInputStream(file); 
			    if(fs != null) 
			        bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); 
			    	bmp = CommonMethod.zoomImg(bmp, ox, oy);
			    	CommonMethod.savePhotoToSDCard(bmp, "myhead");
			  } catch (Exception e) { 
			    e.printStackTrace(); 
			}
		} else {
			closeActivity();
			return;
		}
		progressDialog.show();
		new Thread() {
			@Override
			public void run() {
				CommonMethod.uploadFile(ChangeUserHead.this, 1, handler, 0);
			};
		}.start();
	}
}
